package org.yjc.controller;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.catalina.connector.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.yjc.custom.DatagridUtils;
import org.yjc.entity.Student;
import org.yjc.service.StudentService;

@Controller
public class StudentController {
	@Autowired
	private StudentService studentservice; 
	
	@RequestMapping(value="/001")
	public String index() {
		return "001";
	}
	
	@RequestMapping(value="/002")
	public String layout() {
		return "002";
	}
	
	@RequestMapping(value="/003")
	public String datagrid() {
		return "003";
	}
	
	@RequestMapping(value="/")
	public String login() {
		return "main";
	}
	
	@RequestMapping(value="/save")
	@ResponseBody
	public String save(Student student) {
		studentservice.save(student);
		return "OK";
	}
	
	@RequestMapping(value="/edit")
	@ResponseBody
	public String edit(Student student) {
		Integer id = student.getId();
		student.setId(id);
		studentservice.save(student);
		return "OK";
	}
	
	@RequestMapping(value="/delete")
	@ResponseBody
	public String delete(String ids) {
		String[] ids1 = ids.split(","); //去除“，” 将多个id存入数组中
		for(int i = 0;i < ids1.length;i++) { //循环删除
			studentservice.deleteById(Integer.parseInt(ids1[i]));
		}
		return "OK";
	}
	
	@RequestMapping(value="/findall")
	@ResponseBody
	public Object findall(DatagridUtils param,String name,String stuNum) {
		Pageable pageable = param.buildPageable();
		Page<Student> page = null;
		//安全查询
			Specification<Student> spec = new Specification<Student>() {
				@Override
				public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
					HashSet<Predicate> rules = new HashSet<>();
					if(StringUtils.hasText(name)) {
						rules.add(criteriaBuilder.like(root.get("name"), "%"+name+"%"));
					}else if(StringUtils.hasText(stuNum)) {
						System.out.println(stuNum);
						rules.add(criteriaBuilder.like(root.get("stuNum"), "%"+stuNum+"%"));
					}
					return criteriaBuilder.and(rules.toArray(new Predicate[rules.size()]));
				}
			};
			page = studentservice.findAll(spec,pageable);
		HashMap<String, Object> result = DatagridUtils.getPageResult(page);
		return result;
	}
}
